package com.hmdp.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.KSQLWindow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    /**
     * 将任意Java对象序列化为json并存储在string类型的key中，并且可以设置TTL过期时间
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     * @param <R>
     */
    public <R> void save2JSON(String key,R value,Long time,TimeUnit timeUnit) {
        log.info("save2JSON key:{},value:{}",key,value);
        String jsonStr = JSONUtil.toJsonStr(value);
        //增加随机数防止缓存雪崩
        time = time+ RandomUtil.randomLong(0,5);
        stringRedisTemplate.opsForValue().set(key, jsonStr, time, timeUnit);
    }

    /**
     *将任意Java对象序列化为json并存储在string类型的key中，并且可以设置逻辑过期时间，用于处理缓存击穿问题
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     * @param <R>
     */
    public <R> void save2JSONWithLogic(String key,R value,Long time,TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值（有ttl）的方式解决缓存穿透问题
     * @param keyPrefix
     * @param id
     * @param clazz
     * @param timeout
     * @param timeUnit
     * @param function
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R,ID> R queryWithPassThrough(String keyPrefix,ID id, Class<R> clazz,
                                                Long timeout,
                                                TimeUnit timeUnit,
                                                Function<ID,R> function) {
        //判断数据是否在缓存中
        log.info("queryWithPassThrough keyPrefix:{},id:{}",keyPrefix,id);
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        log.debug("json:{}",json);
        if(StrUtil.isNotBlank(json)) {
            log.info("查询缓存成功");
            return JSONUtil.toBean(json, clazz);
        }
        //字符串不为null,说明是用来防止缓存穿透的空字符串，返回null
        if(json!=null) {
            return null;
        }
        //字符串为空，查询数据库
        R r = function.apply(id);
        log.info("查询数据库");
        //查到，更新缓存
        if(r!=null) {
            log.info("更新缓存");
            this.save2JSON(keyPrefix+id, r, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return r;
        }
        //没查到，存放空字符串
        this.save2JSON(keyPrefix+id,"",timeout,timeUnit);
        return null;
    }

    /**
     * 根据指定的key查询缓存，并反序列化为指定类型，需要利用逻辑过期解决缓存击穿问题
     * @param keyPrefix
     * @param id
     * @param clazz
     * @param timeout
     * @param timeUnit
     * @param function
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id, Class<R> clazz,
                                         Long timeout,
                                         TimeUnit timeUnit,
                                         Function<ID,R> function){
        //查询数据是否在缓存中
        log.info("queryWithLogicalExpire keyPrefix:{},id:{}",keyPrefix,id);
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        log.debug("json:{}",json);
        //不在，返回空
        if(StrUtil.isBlank(json)) {
            return null;
        }
        //在，校验是否过期
        log.info("查询缓存成功");
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //如果没过期直接返回数据
        if(LocalDateTime.now().isBefore(expireTime)) {
            log.info("未过期");
            return JSONUtil.toBean(json, clazz);
        }
        //过期，尝试获取锁
        log.info("逻辑过期");
        //没获取，返回旧数据
        if(!tryGetLock(keyPrefix+id)){
            log.info("获取锁失败");
            return JSONUtil.toBean(json, clazz);
        }
        //获取锁，新线程实现缓存重建
        log.info("获取锁成功");
        executor.execute(()->{
            log.info("开启新线程");
            try {
                log.info("查询数据库");
                R r = function.apply(id);
                log.debug(r.toString());
                log.info("更新缓存");
                this.save2JSONWithLogic(keyPrefix+id, r, timeout, timeUnit);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                log.info("释放锁");
                unlock(keyPrefix+id);
            }

        });
        return JSONUtil.toBean(json, clazz);

    }

    /**
     * 根据指定的key查询缓存，并反序列化为指定类型，需要利用互斥锁解决缓存击穿问题
     * @param keyPrefix
     * @param id
     * @param clazz
     * @param timeout
     * @param timeUnit
     * @param function
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R,ID> R queryWithLock(String keyPrefix,ID id, Class<R> clazz,
                                           Long timeout,
                                           TimeUnit timeUnit,
                                           Function<ID,R> function) throws InterruptedException {
        //查询数据是否在缓存中
        log.info("queryWithLock keyPrefix:{},id:{}",keyPrefix,id);
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        log.debug("json:{}",json);
        //在，直接返回数据
        if(StrUtil.isNotBlank(json)) {
            log.info("缓存查询成功");
            return JSONUtil.toBean(json, clazz);
        }
        //不在，判断是否是空值
        if(json!=null) {
            return null;
        }
        //尝试获取锁
        boolean flag = tryGetLock(keyPrefix + id);
        //获取锁失败，休眠一段时间后重新查询缓存
        if(!flag){
            log.info("获取锁失败");
            Thread.sleep(10);
            return queryWithLock(keyPrefix,id,clazz,timeout,timeUnit,function);
        }
        //获取锁，缓存重建
        log.info("获取锁成功");
        R r = null;
        try {
            log.info("查询数据库");
            r = function.apply(id);
            Thread.sleep(1000);
            if(r==null) {
                log.info("数据不存在数据库");
                stringRedisTemplate.opsForValue().set(keyPrefix+id,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            log.info("缓存更新");
            log.debug(r.toString());
            this.save2JSON(keyPrefix+id, r, timeout, timeUnit);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            log.info("释放锁");
            unlock(keyPrefix+id);
        }
        return r;

    }

    /**
     * 尝试获取锁
     * @return
     */
    private boolean tryGetLock(String key) {
        return stringRedisTemplate.opsForValue().setIfAbsent(RedisConstants.LOCK_KEY+key, "1",10, TimeUnit.SECONDS);
    }

    /**
     * 释放锁
     * @param key
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(RedisConstants.LOCK_KEY+key);
    }


}
